<template>
  <div class="process-container">
    <!-- 顶部操作栏 -->
    <div class="top-bar">
      <a-space>
        <a-button @click="goBack">
          <template #icon>
            <icon-arrow-left />
          </template>
          <template #default>返回</template>
        </a-button>
        <a-button
          type="primary"
          @click="showApproveModal"
          :disabled="
            detailData.purchaseApplicationStatus !== '0' &&
            detailData.purchaseApplicationStatus !== '1'
          "
        >
          <template #default>立即审批</template>
        </a-button>
      </a-space>
    </div>

    <!-- 审批内容 -->
    <div class="process-content" v-loading="loading">
      <!-- 申请基本信息 -->
      <a-card title="申请基本信息" class="mb-4">
        <a-descriptions
          :column="2"
          :label-style="{ width: '120px' }"
          :value-style="{ color: '#1d2129' }"
          bordered
          layout="inline-horizontal"
          size="large"
          title="申请基本信息"
        >
          <a-descriptions-item label="申请名称">
            {{ detailData.purchaseApplicationName || "-" }}
          </a-descriptions-item>
          <a-descriptions-item label="申请编号">
            {{ detailData.purchaseApplicationCode || "-" }}
          </a-descriptions-item>
          <a-descriptions-item label="申请时间">
            {{ detailData.applicationTime || "-" }}
          </a-descriptions-item>
          <a-descriptions-item label="申请状态">
            <a-tag
              :color="getStatusColor(detailData.purchaseApplicationStatus)"
              size="large"
            >
              {{ getStatusText(detailData.purchaseApplicationStatus) }}
            </a-tag>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>

      <!-- 项目信息列表 -->
      <a-card title="项目信息" class="mb-4">
        <a-table
          :columns="projectColumns"
          :data="formData.projectItemList"
          :pagination="false"
          :bordered="true"
          size="medium"
        >
          <template #projectCode="{ record }">
            {{ record.projectCode || "-" }}
          </template>
          <template #projectIndex="{ record }">
            {{ record.projectIndex || "-" }}
          </template>
        </a-table>

        <!-- 项目信息总计 -->
        <div class="mt-4 p-4 bg-gray-50 rounded">
          <a-row :gutter="16">
            <a-col :span="24">
              <span class="font-medium">项目总数：</span>
              <span class="text-blue-600 font-semibold"
                >{{ projectTotal.count }} 个</span
              >
            </a-col>
          </a-row>
        </div>
      </a-card>

      <!-- 镇街信息 -->
      <a-card
        title="镇街指标购买信息"
        class="mb-4"
        v-if="detailData.townItemList && detailData.townItemList.length > 0"
      >
        <a-table
          :columns="townColumns"
          :data="detailData.townItemList"
          :pagination="false"
          :bordered="true"
          size="medium"
        >
          <template #townName="{ record }">
            {{ record.townName || "-" }}
          </template>
          <template #townIndex="{ record }">
            {{ record.townIndex || "-" }}
          </template>
        </a-table>

        <!-- 镇街信息总计 -->
        <div class="mt-4 p-4 bg-gray-50 rounded">
          <a-row :gutter="16">
            <a-col :span="12">
              <span class="font-medium">镇街总数：</span>
              <span class="text-blue-600 font-semibold"
                >{{ townTotal.count }} 个</span
              >
            </a-col>
            <a-col :span="12">
              <span class="font-medium">总购买指标：</span>
              <span class="text-blue-600 font-semibold">{{
                townTotal.totalIndex
              }}</span>
            </a-col>
          </a-row>
        </div>
      </a-card>

      <!-- 确认函模板 -->
      <a-card
        title="确认函模板"
        class="mb-4"
        v-if="confirmationTemplateFiles.length > 0"
      >
        <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
          <a-list-item
            v-for="file in confirmationTemplateFiles"
            :key="file.fileId"
          >
            <a-card size="small" hoverable>
              <a-space>
                <a-avatar :size="28" shape="square">
                  <icon-file-pdf
                    v-if="file.file?.fileType === 'application/pdf'"
                  />
                  <icon-file-image
                    v-else-if="
                      file.file?.fileType &&
                      ['image/jpeg', 'image/jpg', 'image/png'].includes(
                        file.file.fileType
                      )
                    "
                  />
                  <icon-file v-else />
                </a-avatar>
                <div class="file-info">
                  <a-typography-text class="file-name">
                    {{ file.file?.fileName || file.fileName }}
                  </a-typography-text>
                  <div class="file-actions">
                    <a-space size="mini">
                      <a-button
                        size="mini"
                        type="text"
                        @click="downloadFile(file)"
                      >
                        下载
                      </a-button>
                      <a-button
                        size="mini"
                        type="text"
                        @click="previewFile(file)"
                      >
                        预览
                      </a-button>
                    </a-space>
                  </div>
                </div>
              </a-space>
            </a-card>
          </a-list-item>
        </a-list>
      </a-card>

      <!-- 确认函 -->
      <a-card title="确认函" class="mb-4" v-if="confirmationFiles.length > 0">
        <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
          <a-list-item v-for="file in confirmationFiles" :key="file.fileId">
            <a-card size="small" hoverable>
              <a-space>
                <a-avatar :size="28" shape="square">
                  <icon-file-pdf
                    v-if="file.file?.fileType === 'application/pdf'"
                  />
                  <icon-file-image
                    v-else-if="
                      file.file?.fileType &&
                      ['image/jpeg', 'image/jpg', 'image/png'].includes(
                        file.file.fileType
                      )
                    "
                  />
                  <icon-file v-else />
                </a-avatar>
                <div class="file-info">
                  <a-typography-text class="file-name">
                    {{ file.file?.fileName || file.fileName }}
                  </a-typography-text>
                  <div class="file-actions">
                    <a-space size="mini">
                      <a-button
                        size="mini"
                        type="text"
                        @click="downloadFile(file)"
                      >
                        下载
                      </a-button>
                      <a-button
                        size="mini"
                        type="text"
                        @click="previewFile(file)"
                      >
                        预览
                      </a-button>
                    </a-space>
                  </div>
                </div>
              </a-space>
            </a-card>
          </a-list-item>
        </a-list>
      </a-card>

      <!-- 相关附件 -->
      <a-card
        title="相关附件"
        class="mb-4"
        v-if="relatedAttachmentFiles.length > 0"
      >
        <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
          <a-list-item
            v-for="file in relatedAttachmentFiles"
            :key="file.fileId"
          >
            <a-card size="small" hoverable>
              <a-space>
                <a-avatar :size="28" shape="square">
                  <icon-file-pdf
                    v-if="file.file?.fileType === 'application/pdf'"
                  />
                  <icon-file-image
                    v-else-if="
                      file.file?.fileType &&
                      ['image/jpeg', 'image/jpg', 'image/png'].includes(
                        file.file.fileType
                      )
                    "
                  />
                  <icon-file v-else />
                </a-avatar>
                <div class="file-info">
                  <a-typography-text class="file-name">
                    {{ file.file?.fileName || file.fileName }}
                  </a-typography-text>
                  <div class="file-actions">
                    <a-space size="mini">
                      <a-button
                        size="mini"
                        type="text"
                        @click="downloadFile(file)"
                      >
                        下载
                      </a-button>
                      <a-button
                        size="mini"
                        type="text"
                        @click="previewFile(file)"
                      >
                        预览
                      </a-button>
                    </a-space>
                  </div>
                </div>
              </a-space>
            </a-card>
          </a-list-item>
        </a-list>
      </a-card>

      <!-- 审批记录 -->
      <a-card
        title="审批记录"
        v-if="
          detailData.approvalRecords && detailData.approvalRecords.length > 0
        "
      >
        <a-timeline>
          <a-timeline-item
            v-for="(record, index) in detailData.approvalRecords"
            :key="index"
            :dot-color="getApprovalStatusColor(record.status)"
          >
            <template #dot>
              <icon-check-circle v-if="record.status === 'approved'" />
              <icon-close-circle v-else-if="record.status === 'rejected'" />
              <icon-clock-circle v-else />
            </template>
            <div class="approval-item">
              <div class="approval-header">
                <span class="approval-action">{{
                  getApprovalActionText(record.action)
                }}</span>
                <span class="approval-time">{{ record.createTime }}</span>
              </div>
              <div class="approval-user">操作人: {{ record.operatorName }}</div>
              <div class="approval-comment" v-if="record.comment">
                备注: {{ record.comment }}
              </div>
            </div>
          </a-timeline-item>
        </a-timeline>
      </a-card>
    </div>

    <!-- 审批模态框 -->
    <a-modal
      v-model:visible="approveModalVisible"
      title="审批操作"
      width="800px"
      @cancel="resetApproveForm"
    >
      <a-form
        ref="approveFormRef"
        :model="approveForm"
        :rules="approveRules"
        layout="vertical"
      >
        <a-form-item field="result" label="审批结果" required>
          <a-radio-group v-model="approveForm.result">
            <a-radio value="approved">通过</a-radio>
            <a-radio value="rejected">不通过</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item field="comment" label="审批意见">
          <a-textarea
            v-model="approveForm.comment"
            :auto-size="{ minRows: 3, maxRows: 6 }"
            placeholder="请输入审批意见（可选）"
          />
        </a-form-item>

        <!-- 审批通过时的额外信息 -->
        <div v-if="approveForm.result === 'approved'">
          <!-- 审批信息 - 当申请状态不为1时显示 -->
          <div v-if="detailData.purchaseApplicationStatus !== '1'">
            <a-divider orientation="left">审批信息</a-divider>

            <!-- 动态审批信息表单 -->
            <div
              v-for="(approval, index) in approveForm.approvalList"
              :key="index"
              class="mb-4"
            >
              <a-row :gutter="16" align="center">
                <a-col :span="10">
                  <a-form-item
                    :field="`approvalList.${index}.townName`"
                    label="镇街名称"
                    required
                  >
                    <a-select
                      v-model="approval.townName"
                      placeholder="请选择镇街名称"
                    >
                      <a-option
                        v-for="town in dicts[proxy.DICT.lindiTown] || []"
                        :key="town.dictKey"
                        :label="town.dictValue"
                        :value="town.dictValue"
                      >
                        {{ town.dictValue }}
                      </a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="10">
                  <a-form-item
                    :field="`approvalList.${index}.purchasedArea`"
                    label="购买指标(亩)"
                    required
                  >
                    <a-input
                      v-model="approval.purchasedArea"
                      placeholder="请输入购买指标"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-button
                    v-if="approveForm.approvalList.length > 1"
                    type="text"
                    status="danger"
                    @click="removeModalApprovalItem(index)"
                  >
                    删除
                  </a-button>
                </a-col>
              </a-row>
            </div>

            <a-button
              type="dashed"
              @click="addModalApprovalItem"
              class="w-full mb-4"
            >
              <template #icon>
                <icon-plus />
              </template>
              添加审批信息
            </a-button>

            <!-- 审批信息总计 -->
            <div class="mb-4 p-4 bg-blue-50 rounded">
              <a-row :gutter="16">
                <a-col :span="12">
                  <span class="font-medium">审批记录数：</span>
                  <span class="text-blue-600 font-semibold"
                    >{{ modalApprovalTotal.count }} 条</span
                  >
                </a-col>
                <a-col :span="12">
                  <span class="font-medium">总购买指标：</span>
                  <span class="text-blue-600 font-semibold">{{
                    modalApprovalTotal.area
                  }}</span>
                </a-col>
              </a-row>
            </div>
          </div>

          <!-- 确认函上传 - 当申请状态不为0时显示 -->
          <a-form-item
            v-if="detailData.purchaseApplicationStatus !== '0'"
            field="confirmationFile"
            label="确认函"
          >
            <uploadFile
              ref="modalConfirmationUploadRef"
              :file-source="fs"
              :limit="1"
              :multiple="false"
              accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
              list-type="text"
              source-type="proxy"
              @upload-success="handleModalConfirmationUploadSuccess"
            />
            <div class="upload-tip">
              支持格式：PDF、Word文档、图片，文件大小不超过10MB
            </div>
          </a-form-item>
        </div>
      </a-form>

      <template #footer>
        <a-space>
          <a-button @click="resetApproveForm">取消</a-button>
          <a-button
            type="primary"
            :loading="approveLoading"
            @click="handleApprove"
          >
            确认审批
          </a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import {
  computed,
  defineEmits,
  defineProps,
  getCurrentInstance,
  onMounted,
  onBeforeUnmount,
  reactive,
  ref,
  watch,
} from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconArrowLeft,
  IconFile,
  IconFilePdf,
  IconFileImage,
  IconCheckCircle,
  IconCloseCircle,
  IconClockCircle,
  IconUpload,
  IconPlus,
} from "@arco-design/web-vue/es/icon";
import uploadFile from "~/components/uploadFile/index.vue";
import { fileSource } from "~/utils/sys.js";
import {
  getPurchaseApplicationByPurchaseApplicationIdApi,
  approvePurchaseApplicationApi,
} from "~/api/lindi/purchaseApplication.js";
import { deleteFileApi } from "~/api/basic/file.js";

// 定义props
const props = defineProps({
  purchaseApplicationId: {
    type: String,
    required: true,
  },
});

// 定义事件
const emit = defineEmits(["cancel", "ok"]);

// 全局实例
const { proxy } = getCurrentInstance();

// 字典数据
const dicts = proxy.LoadDicts([
  proxy.DICT.lindiProjectType,
  proxy.DICT.lindiPurchaseApplicationStatus,
  proxy.DICT.lindiTown,
]);

// 加载状态
const loading = ref(false);
const submitLoading = ref(false);
const approveLoading = ref(false);
const deleteFileLoading = ref(false);

// 表单引用
const formRef = ref(null);
const confirmationUploadRef = ref(null);
const approveFormRef = ref(null);
const modalConfirmationUploadRef = ref(null);

// 文件来源
const fs =
  fileSource.lindi_purchase_application_confirm_template?.key ||
  "lindi_purchase_application_confirm_template";

// 模态框状态
const approveModalVisible = ref(false);

// 模态框确认函文件列表（保留用于兼容性）
const modalConfirmationFileList = ref([]);

// 跟踪新上传的确认函文件ID，用于取消时清理
const newUploadedConfirmationFileIds = ref([]);

// 附件文件列表
const attachmentFiles = ref([]);

// 详情数据
const detailData = ref({
  purchaseApplicationId: "",
  purchaseApplicationCode: "",
  purchaseApplicationName: "",
  purchaseApplicationStatus: "",
  applicationTime: "",
  createTime: "",
  updateTime: "",
  projectItemList: [],
  approvalRecords: [],
});

// 项目表格列定义
const projectColumns = [
  {
    title: "项目名称",
    dataIndex: "projectName",
    slotName: "projectName",
    width: 200,
  },
  {
    title: "项目编号",
    dataIndex: "projectCode",
    slotName: "projectCode",
    width: 200,
  },
  {
    title: "项目指标",
    dataIndex: "projectIndex",
    slotName: "projectIndex",
    width: 200,
  },
];

// 镇街表格列定义
const townColumns = [
  {
    title: "镇街名称",
    dataIndex: "townName",
    slotName: "townName",
    width: 200,
  },
  {
    title: "购买指标(亩)",
    dataIndex: "townIndex",
    slotName: "townIndex",
    width: 200,
  },
];

// 表单数据（保留用于项目信息显示）
const formData = reactive({
  projectItemList: [],
});

// 审批模态框表单数据
const approveForm = reactive({
  result: "", // approved, rejected
  comment: "",
  confirmationFileId: "",
  approvalList: [{ townName: "", purchasedArea: "" }],
});

// 审批模态框表单规则
const approveRules = computed(() => {
  const baseRules = {
    result: [{ required: true, message: "请选择审批结果" }],
  };

  // 如果是通过操作，需要验证镇街名称和购买指标
  if (approveForm.result === "approved") {
    // 确认函验证已移除 - 不再是必填项

    // 验证动态审批信息列表
    if (detailData.value.purchaseApplicationStatus !== "1") {
      approveForm.approvalList.forEach((_, index) => {
        baseRules[`approvalList.${index}.townName`] = [
          { required: true, message: "请选择镇街名称" },
        ];
        baseRules[`approvalList.${index}.purchasedArea`] = [
          { required: true, message: "请输入购买指标" },
          {
            validator: (value, callback) => {
              if (!value || value.trim() === "") {
                callback("请输入购买指标");
              } else {
                callback();
              }
            },
          },
        ];
      });
    }
  }

  return baseRules;
});

// 项目信息总计
const projectTotal = computed(() => {
  const count = detailData.value.projectItemList?.length || 0;
  return {
    count,
  };
});

// 镇街信息总计
const townTotal = computed(() => {
  const count = detailData.value.townItemList?.length || 0;
  const totalIndex =
    detailData.value.townItemList?.reduce((sum, town) => {
      const value = town.townIndex?.toString().trim();
      if (value && !isNaN(parseFloat(value))) {
        return sum + parseFloat(value);
      }
      return sum;
    }, 0) || 0;
  return {
    count,
    totalIndex: totalIndex > 0 ? `${totalIndex.toFixed(2)} 亩` : "0 亩",
  };
});

// 模态框审批信息总计
const modalApprovalTotal = computed(() => {
  const count = approveForm.approvalList.length;
  const area = approveForm.approvalList.reduce((sum, approval) => {
    const value = approval.purchasedArea?.toString().trim();
    if (value && !isNaN(parseFloat(value))) {
      return sum + parseFloat(value);
    }
    return sum;
  }, 0);
  return {
    count,
    area: area > 0 ? `${area.toFixed(2)} 亩` : "0 亩",
  };
});

// 根据fileType分类附件文件
const confirmationTemplateFiles = computed(() => {
  return attachmentFiles.value.filter((file) => file.fileType === "0");
});

const confirmationFiles = computed(() => {
  console.log("confirmationFiles", attachmentFiles);
  return attachmentFiles.value.filter((file) => file.fileType === "1");
});

const relatedAttachmentFiles = computed(() => {
  return attachmentFiles.value.filter((file) => file.fileType === "2");
});

// 返回列表页
const goBack = () => {
  emit("cancel");
};

// 显示审批模态框
const showApproveModal = () => {
  approveModalVisible.value = true;
};

// 重置审批表单
const resetApproveForm = async (shouldCleanupFiles = true) => {
  approveForm.result = "";
  approveForm.comment = "";
  approveForm.confirmationFileId = "";
  approveForm.approvalList = [{ townName: "", purchasedArea: "" }];
  modalConfirmationFileList.value = [];

  // 只有在需要时才清理未使用的确认函文件
  if (shouldCleanupFiles) {
    await cleanupUnusedConfirmationFiles();
  }

  // 清理uploadFile组件的文件列表
  if (modalConfirmationUploadRef.value) {
    modalConfirmationUploadRef.value.fileList = [];
  }

  approveModalVisible.value = false;
};

// 添加模态框审批信息项
const addModalApprovalItem = () => {
  approveForm.approvalList.push({ townName: "", purchasedArea: "" });
};

// 删除模态框审批信息项
const removeModalApprovalItem = (index) => {
  if (approveForm.approvalList.length > 1) {
    approveForm.approvalList.splice(index, 1);
  }
};

// 获取状态颜色
const getStatusColor = (status) => {
  if (!status || !dicts[proxy.DICT.lindiPurchaseApplicationStatus]) {
    return "gray";
  }
  const dict = dicts[proxy.DICT.lindiPurchaseApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict?.dictClass || "gray";
};

// 获取状态文本
const getStatusText = (status) => {
  if (!status || !dicts[proxy.DICT.lindiPurchaseApplicationStatus]) {
    return "未知状态";
  }
  const dict = dicts[proxy.DICT.lindiPurchaseApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict ? dict.dictValue : "未知状态";
};

// 获取项目类型文本
const getProjectTypeText = (projectType) => {
  const typeDict = dicts[proxy.DICT.lindiProjectType] || [];
  const typeItem = typeDict.find((item) => item.dictKey === projectType);
  return typeItem ? typeItem.dictValue : projectType || "未知类型";
};

// 获取审批状态颜色
const getApprovalStatusColor = (status) => {
  const colors = {
    approved: "#00b42a",
    rejected: "#f53f3f",
    pending: "#ff7d00",
  };
  return colors[status] || "#86909c";
};

// 获取审批操作文本
const getApprovalActionText = (action) => {
  const actions = {
    submit: "提交申请",
    approve: "审批通过",
    reject: "审批拒绝",
    return: "退回修改",
  };
  return actions[action] || action || "未知操作";
};

// 处理模态框确认函上传成功
const handleModalConfirmationUploadSuccess = (response) => {
  console.log("确认函上传成功:", response);
  if (response && response.fileId) {
    approveForm.confirmationFileId = response.fileId;
    newUploadedConfirmationFileIds.value.push(response.fileId);
    // 更新modalConfirmationFileList以保持数据一致性
    modalConfirmationFileList.value = [response];
    Message.success("确认函上传成功");
  }
};

// 处理模态框确认函删除（uploadFile组件内部会处理实际删除）
const handleModalConfirmationRemove = (fileId) => {
  // 清理相关状态
  if (fileId) {
    const index = newUploadedConfirmationFileIds.value.indexOf(fileId);
    if (index > -1) {
      newUploadedConfirmationFileIds.value.splice(index, 1);
    }
  }

  approveForm.confirmationFileId = "";
  // 清理modalConfirmationFileList
  modalConfirmationFileList.value = [];
  console.log("确认函文件已删除，清理相关状态");
};

// 清理未使用的确认函文件
const cleanupUnusedConfirmationFiles = async () => {
  for (const fileId of newUploadedConfirmationFileIds.value) {
    try {
      await deleteFileApi(fileId);
      console.log("已清理确认函文件:", fileId);
    } catch (error) {
      console.error("清理确认函文件失败:", error);
    }
  }
  newUploadedConfirmationFileIds.value = [];
};

// 下载附件文件
const downloadFile = (file) => {
  const fileUrl = file.file?.fileUrl || file.fileUrl;
  if (fileUrl) {
    window.open(fileUrl, "_blank");
  } else {
    Message.error("文件下载链接不存在");
  }
};

// 预览附件文件
const previewFile = (file) => {
  const fileUrl = file.file?.fileUrl || file.fileUrl;
  if (fileUrl) {
    window.open(fileUrl, "_blank");
  } else {
    Message.error("文件预览链接不存在");
  }
};

// 获取购买申请详情
const getPurchaseApplicationDetail = () => {
  if (!props.purchaseApplicationId) {
    Message.error("缺少申请ID");
    return;
  }

  loading.value = true;

  getPurchaseApplicationByPurchaseApplicationIdApi(props.purchaseApplicationId)
    .then((response) => {
      const res = response;
      console.log("获取购买申请详情成功:", res);

      detailData.value = {
        purchaseApplicationId: res.purchaseApplicationId,
        purchaseApplicationCode: res.purchaseApplicationCode,
        purchaseApplicationName: res.purchaseApplicationName,
        purchaseApplicationStatus: res.purchaseApplicationStatus,
        applicationTime: res.applicationTime,
        createTime: res.createTime,
        updateTime: res.updateTime,
        projectItemList: res.projectItemList || [],
        townItemList: res.townItemList || [],
        approvalRecords: res.approvalRecords || [],
      };

      // 初始化表单数据
      formData.projectItemList = (res.projectItemList || []).map((project) => ({
        ...project,
        townName: project.townName || "",
        purchasedArea: project.purchasedArea || null,
        approvalComment: "",
      }));

      // 初始化附件文件数据
      attachmentFiles.value = res.fileList || [];
    })
    .catch((error) => {
      console.error("获取购买申请详情失败:", error);
      Message.error("获取详情失败: " + (error.message || "网络错误"));
    })
    .finally(() => {
      loading.value = false;
    });
};

// 处理审批提交
const handleApprove = () => {
  // 验证表单
  approveFormRef.value
    .validate()
    .then((errors) => {
      if (errors) {
        return;
      }

      approveLoading.value = true;

      // 构建提交数据，符合LindiPurchaseApplicationApprovalVO结构
      const submitData = {
        purchaseApplicationId: props.purchaseApplicationId, // 直接传递字符串，避免溢出
        approvalResult: approveForm.result === "approved" ? 1 : 2, // 1-通过，2-驳回
        approvalComment: approveForm.comment || "", // 审批意见，可选
        townItemList:
          approveForm.result === "approved"
            ? approveForm.approvalList.map((item) => ({
                townName: item.townName,
                townIndex: item.purchasedArea, // 将purchasedArea映射为townIndex
              }))
            : null, // 只有审批通过时才提交镇街指标数据
        confirmationFileId:
          approveForm.result === "approved" && approveForm.confirmationFileId
            ? approveForm.confirmationFileId
            : null, // 只有审批通过且有确认函文件时才提交
      };

      console.log("提交审批数据:", submitData);

      approvePurchaseApplicationApi(submitData)
        .then((response) => {
          console.log("审批响应:", response);
          Message.success("审批提交成功");

          // 如果审批成功且有确认函文件，清空待删除列表（文件已被正式使用）
          if (
            approveForm.result === "approved" &&
            approveForm.confirmationFileId
          ) {
            newUploadedConfirmationFileIds.value = [];
          }

          // 审批成功后不清理文件，因为文件已被正式使用
          const shouldCleanupFiles = !(
            approveForm.result === "approved" && approveForm.confirmationFileId
          );
          resetApproveForm(shouldCleanupFiles);
          // 重新加载详情数据
          getPurchaseApplicationDetail();
          emit("ok");
        })
        .catch((error) => {
          console.error("审批提交失败:", error);
          Message.error("审批提交失败: " + (error.message || "网络错误"));
        })
        .finally(() => {
          approveLoading.value = false;
        });
    })
    .catch((error) => {
      console.error("表单验证失败:", error);
    });
};

// 提交审批（保留原方法以防其他地方调用）
const submitApproval = () => {
  // 现在通过模态框处理审批
  showApproveModal();
};

// 初始化
onMounted(() => {
  getPurchaseApplicationDetail();
});

// 组件卸载时清理未使用的文件
onBeforeUnmount(async () => {
  if (newUploadedConfirmationFileIds.value.length > 0) {
    await cleanupUnusedConfirmationFiles();
  }
});
</script>

<style scoped>
.process-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.top-bar {
  padding: 16px 24px;
  border-bottom: 1px solid #e5e6eb;
  background: #fff;
  flex-shrink: 0;
}

.process-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: #f7f8fa;
}

.project-list {
  max-width: 100%;
}

.project-card {
  margin-bottom: 16px;
}

.project-card :deep(.arco-card-header) {
  background: #f2f3f5;
  border-bottom: 1px solid #e5e6eb;
}

.project-card :deep(.arco-card-body) {
  background: #fff;
}

.situation-text {
  line-height: 1.6;
  word-break: break-word;
  white-space: pre-wrap;
}

.file-section {
  margin-bottom: 16px;
}

.file-label {
  font-weight: 600;
  margin-bottom: 8px;
  color: #1d2129;
}

.file-content {
  margin-left: 16px;
}

.image-preview {
  display: inline-block;
  text-align: center;
}

.image-name {
  margin-top: 8px;
  font-size: 12px;
  color: #86909c;
  max-width: 200px;
  word-break: break-word;
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.no-file {
  color: #86909c;
  font-style: italic;
}

.approval-item {
  padding: 8px 0;
}

.approval-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.approval-action {
  font-weight: 600;
  color: #1d2129;
}

.approval-time {
  color: #86909c;
  font-size: 12px;
}

.approval-user {
  color: #4e5969;
  font-size: 14px;
  margin-bottom: 4px;
}

.approval-comment {
  color: #4e5969;
  font-size: 14px;
  background: #f7f8fa;
  padding: 8px;
  border-radius: 4px;
  border-left: 3px solid #165dff;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #86909c;
  line-height: 1.4;
}
</style>
